package com.clip.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class URLReplace {
	private static final String SUB_DOMAIN = "(?i:[a-z0-9]|[a-z0-9][-a-z0-9]*[a-z0-9])";
	// 顶级域名
	private static final String TOP_DOMAINS = "(?x-i:com\\b        \n"
			+ "     |edu\\b        \n" + "     |biz\\b        \n"
			+ "     |in(?:t|fo)\\b \n" + "     |mil\\b        \n"
			+ "     |net\\b        \n" + "     |org\\b        \n"
			+ "     |[a-z][a-z]\\b \n" + // 国家代码
			")                   \n";
	// 主机名
	private static final String HOSTNAME = "(?:" + SUB_DOMAIN + "\\.)+"
			+ TOP_DOMAINS;

	// URL 地址中不允许包括的字符，以及其他的条件
	private static final String NOT_IN = ";:\"'<>()\\[\\]{}\\s\\x7F-\\xFF";
	private static final String NOT_END = "!.,?";
	private static final String ANYWHERE = "[^" + NOT_IN + NOT_END + "]";
	private static final String EMBEDDED = "[" + NOT_END + "]";
	private static final String URL_PATH = "/" + ANYWHERE + "*(" + EMBEDDED
			+ "+" + ANYWHERE + "+)*";

	// 端口号 0～65535
	private static final String PORT = "(?:                          \n"
			+ "  [0-5]?[0-9]{1,4}           \n"
			+ "  |                          \n"
			+ "  6(?:                       \n"
			+ "     [0-4][0-9]{3}           \n"
			+ "     |                       \n"
			+ "     5(?:                    \n"
			+ "        [0-4][0-9]{2}        \n"
			+ "        |                    \n"
			+ "        5(?:                 \n"
			+ "           [0-2][0-9]        \n"
			+ "           |                 \n"
			+ "           3[0-5]            \n"
			+ "         )                   \n"
			+ "      )                      \n"
			+ "   )                         \n" + ")";

	// URL 表达式
	private static final String URL = "(?x:                                                \n"
			+ "  \\b                                               \n"
			+ "  (?:                                               \n"
			+ "    (?: ftp | http s? ): // [-\\w]+(\\.\\w[-\\w]*)+ \n"
			+ "   |                                                \n"
			+ "    "
			+ HOSTNAME
			+ "                                \n"
			+ "  )                                                 \n"
			+ "  (?: : "
			+ PORT
			+ " )?                             \n"
			+ "  (?: " + URL_PATH + ")?                            \n" + ")";

	public static String replace(String content) {
		if(content==null||content.length()==0)
			return "";
		Pattern pattern = Pattern.compile(URL);
		Matcher matcher = pattern.matcher(content);
		StringBuffer result = new StringBuffer();
		while (matcher.find()) {
			StringBuffer replace = new StringBuffer();
			replace.append("<a href=\"");
			String str = matcher.group();
			if(checkIsEmail(content,str))
				continue;
			if (!str.startsWith("http:") && !str.startsWith("https:")
					&& !str.startsWith("ftp:"))
				replace.append("http://");
			replace.append(matcher.group());
			replace.append("\" target=\"_blank\">").append(matcher.group())
					.append("</a>");
			matcher.appendReplacement(result, replace.toString());
		}
		matcher.appendTail(result);
		return result.toString();
	}

	public static boolean checkIsEmail(String content,String str){
		int pos=content.indexOf(str);
		if(pos==0)
			return false;
		else{
			pos--;
			char poschar=content.charAt(pos);
			if(poschar=='@')
				return true;
			else
				return false;
		}
	}

	public static void main(String[]args){
		String str="<p>http://www.sh-anfang.org/Item/Show.asp?m=1&d=3604</p>";
		System.out.println(replace(str));
	}
}
